package com.xiyou.luckdraw.api.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiyou.luckdraw.api.converter.AnswerBankConverter;
import com.xiyou.luckdraw.api.dal.entitys.AnswerBank;
import com.xiyou.luckdraw.api.dal.entitys.UserInfo;
import com.xiyou.luckdraw.api.dal.mapper.luckdraw.AnswerBank1Mapper;
import com.xiyou.luckdraw.api.dal.mapper.luckyelite.AnswerBank2Mapper;
import com.xiyou.luckdraw.api.dto.answer.*;
import com.xiyou.luckdraw.api.dto.user.UserInfoListRequest;
import com.xiyou.luckdraw.api.service.IAnswerBankService;
import com.xiyou.luckdraw.common.constants.ResultCodeConstants;
import com.xiyou.luckdraw.common.enums.AnswerBankEnum;
import com.xiyou.luckdraw.common.exception.ExceptionProcessorUtils;
import com.xiyou.luckdraw.common.utils.DateUtils;
import com.xiyou.luckdraw.common.utils.ExcelUtils;
import com.xiyou.luckdraw.common.utils.ReqUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: AnswerBankServiceImpl
 * @Description:
 * @author: limingxing
 * @Date: 2019-10-09 10:56
 */
@Slf4j
@Service
public class AnswerBankServiceImpl implements IAnswerBankService {

    @Autowired
    private AnswerBank1Mapper answerBank1Mapper;

    @Autowired
    private AnswerBank2Mapper answerBank2Mapper;
    @Autowired
    private AnswerBankConverter answerBankConverter;

    @Override
    public AddAnswerBankResponse createAnswer(AddAnswerBankRequest request) {
        log.error("Begin AnswerBankServiceImpl.createAnswer request : {}", request);
        AddAnswerBankResponse response = new AddAnswerBankResponse();
        try {
            AnswerBank answerBank = answerBankConverter.req2Answer(request);
            answerBank.setModifyTime(new Date());
            answerBank.setCreateTime(new Date());
            String datasourceType = ReqUtils.getDatasourceType();
            int row = 0;
            Example example = new Example(AnswerBank.class);
            if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                List answerBanks = answerBank1Mapper.selectByExample(example);
                if (null == answerBanks || answerBanks.isEmpty()) {
                    row = answerBank1Mapper.insertSelective(answerBank);
                }
            } else {
                List answerBanks = answerBank1Mapper.selectByExample(example);
                if (null == answerBanks || answerBanks.isEmpty()) {
                    row = answerBank2Mapper.insertSelective(answerBank);
                }
            }
            response.setCode(ResultCodeConstants.SUCCESS.getCode());
            response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
            log.info("AnswerBankServiceImpl.createAnswer effect row : {}", row);
        } catch (Exception e) {
            log.error("AnswerBankServiceImpl.createAnswer Occur Exception : {}", e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public AnswerBankListResponse getAnswerList(AnswerBankListRequest request) {
        log.error("Begin AnswerBankServiceImpl.getAnswerList request : {}", request);
        AnswerBankListResponse response = new AnswerBankListResponse();
        try {
            request.requestCheck();
            PageHelper.startPage(request.getPage(), request.getSize());
            if(StringUtils.isNotEmpty(request.getStartTime())){
                request.setStartTime(DateUtils.timeStamp2Date(request.getStartTime(),"YYYY-MM-dd"));
            }
            if(StringUtils.isNotEmpty(request.getEndTime())){
                request.setEndTime(DateUtils.timeStamp2Date(request.getEndTime(),"YYYY-MM-dd"));
            }
            String datasourceType = ReqUtils.getDatasourceType();
            List<AnswerBank> answerBankList = null;
            if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                answerBankList = answerBank1Mapper.selectAnswerList(request);
            } else {
                answerBankList = answerBank2Mapper.selectAnswerList(request);
            }

            PageInfo<AnswerBank> pageInfo = new PageInfo<>(answerBankList);

            List<AnswerBankDto> answerBankDtos = answerBankConverter.answerBanks2Dto(pageInfo.getList());
            response.setTotal(pageInfo.getTotal());
            response.setAnswerBankDtos(answerBankDtos);
            response.setCode(ResultCodeConstants.SUCCESS.getCode());
            response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("AnswerBankServiceImpl.getAnswerList Occur Exception : {}", e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteAnswerResponse updateByAnswerId(DeleteAnswerRequest request) {
        log.error("Begin AnswerBankServiceImpl.updateByAnswerId request : {}", request);
        DeleteAnswerResponse response = new DeleteAnswerResponse();
        try {
            request.requestCheck();
            AnswerBank answer = new AnswerBank();
            answer.setId(request.getAnswerId());
            answer.setStatus(request.getStatus());
            String datasourceType = ReqUtils.getDatasourceType();
            int row = 0;
            if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                row = answerBank1Mapper.updateByPrimaryKeySelective(answer);
            } else {
                row = answerBank2Mapper.updateByPrimaryKeySelective(answer);
            }
            response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
            response.setCode(ResultCodeConstants.SUCCESS.getCode());
            log.info("AnswerBankServiceImpl.updateByAnswerId effect row : {}", row);
        } catch (Exception e) {
            log.error("AnswerBankServiceImpl.updateByAnswerId Occur Exception : {}", e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public UpdateAnswerResponse updateAnswer(UpdateAnswerRequest request) {
        log.error("Begin AnswerBankServiceImpl.updateAnswer request : {}", request);
        UpdateAnswerResponse response = new UpdateAnswerResponse();
        try {
            AnswerBank answer = answerBankConverter.req2Answer(request);
            answer.setId(request.getAnswerId());
            answer.setModifyTime(new Date());
            String datasourceType = ReqUtils.getDatasourceType();
            int row = 0;
            if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                row = answerBank1Mapper.updateByPrimaryKeySelective(answer);
            } else {
                row = answerBank2Mapper.updateByPrimaryKeySelective(answer);
            }
            response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
            response.setCode(ResultCodeConstants.SUCCESS.getCode());
            log.info("AnswerBankServiceImpl.updateAnswer effect row : {}", row);
        } catch ( Exception e ) {
            log.error("AnswerBankServiceImpl.updateAnswer Occur Exception : {}", e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public ExcelResponse readExcelFile(MultipartFile file) {
        log.error("Begin AnswerBankServiceImpl.readExcelFile file : {}", file);
        System.out.println("Header: " + ReqUtils.getDatasourceType());
        ExcelResponse response = new ExcelResponse();
        if (null != file) {
            List<AnswerBank> list = getExcelInfo(file);
            if (null != list && !list.isEmpty()) {
                String datasourceType = ReqUtils.getDatasourceType();
                for (AnswerBank obj : list) {
                    obj.setCreateTime(new Date());
                    obj.setModifyTime(new Date());
                    obj.setStatus(new Long(1));
                    Example example = new Example(AnswerBank.class);
                    example.createCriteria().andEqualTo("answerTitle", obj.getAnswerTitle());
                    if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                        List answerBanks = answerBank1Mapper.selectByExample(example);
                        if (null == answerBanks || answerBanks.isEmpty()) {
                            int row = answerBank1Mapper.insert(obj);
                            log.info("luckdraw answerBank1Mapper insert: {},    返回结果： {}", obj, row);
                        }
                    } else {
                        List answerBanks = answerBank2Mapper.selectByExample(example);
                        if (null == answerBanks || answerBanks.isEmpty()) {
                            int row = answerBank2Mapper.insert(obj);
                            log.info("luckyelite answerBank2Mapper insert: {},    返回结果： {}", obj, row);
                        }
                    }

                }
            }
        }
        response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
        response.setCode(ResultCodeConstants.SUCCESS.getCode());
        return response;
    }

    @Override
    public List downloadAnswerExcel(HttpServletRequest servletRequest) {
        log.error("Begin UserInfoServiceImpl.updateByUserId request ");
        try {
            Example example = new Example(AnswerBank.class);
            String startTime = servletRequest.getParameter("starTime");
            if (startTime != null && !startTime.equals("")) {
                example.createCriteria().andGreaterThanOrEqualTo("createTime", startTime);
            }
            String endTime = servletRequest.getParameter("endTime");
            if (endTime != null && !endTime.equals("")) {
                example.createCriteria().andLessThanOrEqualTo("createTime", endTime);
            }

            String datasourceType = servletRequest.getParameter("datasourceType");
            List<AnswerBank> answerList = null;

            if(StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)){
                answerList = answerBank1Mapper.selectByExample(example);
            }else {
                answerList = answerBank2Mapper.selectByExample(example);
            }
            List<Map> resultList = new ArrayList<>();
            for(AnswerBank answer : answerList){
                Map map = new HashMap();
                map.put("id",answer.getId());
                map.put("answerTitle",answer.getAnswerTitle());
                map.put("A",answer.getA());
                map.put("B",answer.getB());
                map.put("C",answer.getC());
                map.put("D",answer.getD());
                map.put("E",answer.getE());
                map.put("correctAnswer",answer.getCorrectAnswer());
                if(1 == answer.getStatus()){
                    map.put("status","启用");
                }else if(2 == answer.getStatus()){
                    map.put("status","弃用");
                }
                map.put("level",answer.getLevel());
                map.put("createTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(answer.getCreateTime()));
                resultList.add(map);
            }
            return resultList;
        } catch (Exception e) {
            log.error("UserInfoServiceImpl.getUserList Occur Exception : {}", e);
        }
        return null;
    }

    @Override
    public ExcelResponse saveList(ExcelAnswerListRequest request) {
        log.error("Begin UserInfoServiceImpl.saveList request ");
        ExcelResponse response = new ExcelResponse();
        try {
            List<AnswerBankDto>  list = request.getSaveList();
            String datasourceType = ReqUtils.getDatasourceType();
            List<AnswerBank> answerBankList = answerBankConverter.req2ListAnswer(list);
            for (AnswerBank obj : answerBankList) {
                obj.setCreateTime(new Date());
                obj.setModifyTime(new Date());
                obj.setStatus(new Long(1));
                if (StringUtils.isNotBlank(datasourceType) && "luckdraw".equals(datasourceType)) {
                    AnswerBank answerBan = answerBank1Mapper.selectByAnswerTitle( obj.getAnswerTitle());
                    if (null == answerBan) {
                        int row = answerBank1Mapper.insert(obj);
                        log.info("luckdraw answerBank1Mapper insert: {},    返回结果： {}", obj, row);
                    }
                } else {
                    AnswerBank answerBank = answerBank2Mapper.selectByAnswerTitle(obj.getAnswerTitle());
                    if (null == answerBank) {
                        int row = answerBank2Mapper.insert(obj);
                        log.info("luckyelite answerBank2Mapper insert: {},    返回结果： {}", obj, row);
                    }
                }
            }
            response.setMsg(ResultCodeConstants.SUCCESS.getMessage());
            response.setCode(ResultCodeConstants.SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * * 读EXCEL文件，获取信息集合 
     * * @param fielName 
     * * @return 
     */
    public List<AnswerBank> getExcelInfo(MultipartFile multipartFile) {
        log.error("Begin AnswerBankServiceImpl.getExcelInfo");
        String fileName = multipartFile.getOriginalFilename();//获取文件名  
        List<AnswerBank> answerList = new ArrayList<>();
        try {
            if (!new ExcelUtils().validateExcel(fileName)) {// 验证文件名是否合格  
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本  
            if (ExcelUtils.isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            answerList = createExcel(multipartFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("End AnswerBankServiceImpl.getExcelInfo answerList: {}", answerList);
        return answerList;
    }

    /**
     *  
     * * 根据excel里面的内容读取客户信息 
     * * @param is 输入流 
     * * @param isExcel2003 excel是2003还是2007版本 
     * * @return 
     * * @throws IOException 
     *    
     */
    public List createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003  
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007  
                wb = new XSSFWorkbook(is);
            }
            List answerList = readExcelValue(wb);// 读取Excel里面客户的信息  
            return answerList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /**
     *  
     * * 读取Excel里面客户的信息 
     * * @param wb 
     * * @return 
     *    
     */
    private List<AnswerBank> readExcelValue(Workbook wb) {// 得到第一个shell
        log.info("Begin AnswerBankServiceImpl.readExcelValue");
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数  
        ExcelUtils.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)  
        if (ExcelUtils.totalRows > 1 && sheet.getRow(0) != null) {
            ExcelUtils.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<AnswerBank> answerList = new ArrayList<AnswerBank>();
        // 循环Excel行数  
        for (int r = 1; r < ExcelUtils.totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            AnswerBank answer = new AnswerBank();// 循环Excel的列  
            for (int c = 0; c < ExcelUtils.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell  && !cell.equals("")) {
                    if (c == 0) {//如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25  
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String title = String.valueOf(cell.getNumericCellValue());
                            answer.setAnswerTitle(title.substring(0, title.length() - 2 > 0 ? title.length() - 2 : 1));
                        } else {
                            answer.setAnswerTitle(cell.getStringCellValue());
                        }

                    } else if (c == 1) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String A = String.valueOf(cell.getNumericCellValue());
                            answer.setA(A.substring(0, A.length() - 2 > 0 ? A.length() - 2 : 1));
                        } else {
                            answer.setA(cell.getStringCellValue());
                        }
 //                       answer.setA(cell.getStringCellValue());
                    } else if (c == 2) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String B = String.valueOf(cell.getNumericCellValue());
                            answer.setB(B.substring(0, B.length() - 2 > 0 ? B.length() - 2 : 1));
                        } else {
                            answer.setB(cell.getStringCellValue());
                        }
//                        answer.setB(cell.getStringCellValue());
                    } else if (c == 3) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String C = String.valueOf(cell.getNumericCellValue());
                            answer.setC(C.substring(0, C.length() - 2 > 0 ? C.length() - 2 : 1));
                        } else {
                            answer.setC(cell.getStringCellValue());
                        }
//                        answer.setC(cell.getStringCellValue());
                    } else if (c == 4) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String D = String.valueOf(cell.getNumericCellValue());
                            answer.setD(D.substring(0, D.length() - 2 > 0 ? D.length() - 2 : 1));
                        } else {
                            answer.setD(cell.getStringCellValue());
                        }
//                        answer.setD(cell.getStringCellValue());
                    } else if (c == 5) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String correctAnswer = String.valueOf(cell.getNumericCellValue());
                            answer.setCorrectAnswer(new Long(correctAnswer.substring(0, correctAnswer.length() - 2 > 0 ? correctAnswer.length() - 2 : 1)));
                        } else {
                            System.out.println("----------------"+ cell);
                            if(!cell.equals("")) {
                                answer.setCorrectAnswer(new Long(cell.getStringCellValue().trim()));
                            }else {
                                System.out.println("************"+ cell.getStringCellValue());
                            }
                        }

                    } else if (c == 6) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String sex = String.valueOf(cell.getNumericCellValue());
                            answer.setLevel(new Long(sex.substring(0, sex.length() - 2 > 0 ? sex.length() - 2 : 1)));
                        } else {
                            answer.setLevel(new Long(cell.getStringCellValue()));
                        }
                    }
                }
            }// 添加到list
            log.info("answerList add answer: {}", answer);
            answerList.add(answer);
        }
        return answerList;
    }


}
